import {
  ProForm,
  ProFormCheckbox,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import { Descriptions, Form, Modal, Space, Tooltip, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { history } from "umi";
import "./index.less";
import { PaddingContent } from "@/components/page-padding";
import { CustomSubTitle, CustomTitle } from "@/components/customTitle";
import { StyledAgree, StyledCancel } from "@/components/button";
import { StyledAlertCircle, StyledTextAlign } from "@/components/common-styled";
import styled from "styled-components";
import { saveIdVerify } from "@/services/identity-verification";
import userStore from "@/store/userStore";

const CenterDiv = styled("div")`
   display: "felex",
   alignItems: "center"
`;

const IdentityVerification = () => {
  const { userId, updateIdentityData, identityData } = userStore();
  //console.log("identityData:", identityData);

  const userExists = (userId: any) => {
    if (userId !== "" && userId !== undefined && userId !== null) {
      return true;
    }
    return false;
  };

  const [selectedValue, setSelectedValue] = useState("Select a Type");

  const handleSelectChange = (value: any) => {
    setSelectedValue(value);
  };

  const [form] = Form.useForm<any>();

  // 控制模态框的显示状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // company下拉框
  // const [selectedOption, setSelectedOption] = useState("");
  // 输入框的验证码
  const [optCode, setOptCode] = useState(["", "", "", "", "", ""]);
  // 验证码错误信息
  const [optError, setOptError] = useState("");
  // 是否验证失败（标志输入框的状态）
  const [isValidFail, setIsValidFail] = useState(false);
  // 是否已验证成功（标志验证码按钮的状态）
  const [isVerified, setIsVerified] = useState(
    userExists(userId) ? true : false
  );
  // Mobile输入框的值
  const [mobile, setMobile] = useState<number>();
  // 计数器
  const [countdown, setCountdown] = useState(0);
  // 给验证码的每个输入框绑定一个引用
  const inputRefs = useRef<(HTMLInputElement | null)[]>(Array(6).fill(null));

  const [myMap, setMyMap] = useState(new Map());
  // 在 useEffect 钩子中进行初始的设置
  useEffect(() => {
    setMyMap(
      new Map([
        ["home", "/"],
        ["identity", "/identity"],
      ])
    );
  }, []);

  const toRedirect = (value: string) => {
    history.push(myMap.get(value));
  };

  // 取消按钮恢复验证码状态
  const handleCancel = () => {
    setIsModalOpen(false);
    setOptCode(["", "", "", "", "", ""]);
    setOptError("");
    setIsValidFail(false);
  };
  // // 下拉框改变事件
  // const handleChangeOption = (e: React.ChangeEvent<HTMLSelectElement>) => {
  //   setSelectedOption(e.target.value);
  // };

  // 电话框只能输入数字
  const handleChangeMobile = (value: number) => {
    setIsVerified(false);
    setMobile(value);
    if (value && value.toString().length !== 8) {
      console.log("输入的数字不是 8 位");
    }
    // }
  };
  // 验证码发送按钮
  const handleSendOpt = () => {
    console.log("发送验证码");
    // 是八位数字才能发送验证码

    console.log(mobile, " type");
    if (mobile?.toString().length === 8) {
      setIsModalOpen(true);
      // 当秒数为0才能重新发送验证码
      if (countdown === 0) {
        setCountdown(60);
      }
    } else {
      message.error({ content: "mobile phone length is eight" });
    }
  };

  // 设置定时器
  // useEffect(() => {
  //     const timer = setInterval(() => {
  //         if (countdown > 0) {
  //             setCountdown(countdown - 1);
  //         } else {
  //             clearInterval(timer);
  //         }
  //     }, 1000);

  //     return () => clearInterval(timer);
  // }, [countdown]);

  // 验证码输入框改变事件
  const handleChange = (index: number, value: string) => {
    if (value.length === 1 && /^\d$/.test(value)) {
      const newCode = [...optCode];
      newCode[index] = value;
      setOptCode(newCode);
      console.log("newCode", newCode);
      console.log("setOptCode", optCode);

      if (index < 5) {
        console.log("光标自动换下一个input");
        inputRefs.current[index + 1]?.focus();
      }
    } else if (value.length === 0) {
      console.log("删除验证码");
      setOptError("");
      setIsValidFail(false);
      const newCode = [...optCode];
      newCode[index] = value;
      setOptCode(newCode);
      inputRefs.current[index - 1]?.focus();
      //index = index - 1;
    }
  };

  useEffect(() => {
    // 更新 optCode的值是异步的,若要看到最新值则组要useEffect钩子
    // 输入完成在此处处理验证码验证逻辑
    if (optCode.filter((item) => item !== "").length === 6) {
      const optCodeStr = optCode.toString().replace(/,/g, "");
      if (optCodeStr === "123456") {
        // 关闭弹框
        setIsModalOpen(false);
        setIsVerified(true);
        console.log("验证成功，验证码：", optCode.join(""));
      } else {
        setIsValidFail(true);
        setOptError("OTP does not match. Please re-enter the correct code.");
      }
    }

    // 设置定时器
    const timer = setInterval(() => {
      if (countdown > 0) {
        setCountdown(countdown - 1);
      } else {
        clearInterval(timer);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [optCode, countdown]);

  // 键盘按键事件
  const handleKeyDown = (
    index: number,
    event: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (event.key === "ArrowLeft" && index > 0) {
      inputRefs.current[index - 1]?.focus();
    } else if (event.key === "ArrowRight" && index < 5) {
      inputRefs.current[index + 1]?.focus();
    }
  };

  // 给验证码的每个输入框绑定一个引用
  const handleInputRef = (index: number, ref: HTMLInputElement | null) => {
    inputRefs.current[index] = ref;
  };

  const onFinish = async (values: any) => {
    console.log("Form values onFinish = ", values);
    // return;
    if (isVerified && selectedValue !== "Select a Type") {
      if (userExists(userId)) {
        history.push({
          pathname: "/identity",
          search: `?company=${selectedValue}&mobile=${values.mobile}&
crewMember=${values?.crewMember} &specify=${values?.specify}`,
        });
        return;
      }
      //return;
      // 处理提交逻辑
      // call api
      saveIdVerify({
        email: values.email,
        hkiaId: "00000001",
        englishName: values.fullNameEn,
        chineseName: values.fullNameCn,
        companyId: "2DE8F2A6-F71A-46BB-8B9B-3676BEE91165",
        otherCompany: "00002",
        mobile: values.mobile,
        crewMember: "00001",
      })
        .then((data) => {
          console.log("Form values saveIdVerify", data);
          //@ts-ignore
          if (data.code === 200) {
            updateIdentityData({
              ...identityData,
              mobile: values.mobile,
              // companyId: selectedValue,
            });
            const newIdentityData = {};
            history.push({
              pathname: "/identity",
              search: `?company=${selectedValue}&mobile=${values.mobile}&
crewMember=${values?.crewMember} &specify=${values?.specify}`,
            });
          }
        })
        .catch((error) => {
          console.error(error, "error");
        });
    } else {
      message.error({ content: "please check Mobile and Company" });
    }

    // console.log("Form values:", values);
  };

  return (
    <>
      <PaddingContent>
        <div className="identity-verification">
          <CustomTitle>
            IdentityForm Verification & License Plate Number Registration
          </CustomTitle>

          <div className="identity-content">
            <ProForm
              initialValues={{
                fullNameEn: identityData?.englishName,
                fullNameCn: identityData?.chineseName,
                email: identityData?.email,
              }}
              form={form}
              onFinish={onFinish}
              submitter={{
                render: (props) => (
                  <StyledTextAlign>
                    <Space size="large">
                      <StyledCancel
                        type="default"
                        onClick={() => toRedirect("home")}
                        className="footer-button"
                      >
                        Cancel
                      </StyledCancel>
                      <StyledAgree
                        onClick={() => props.form?.submit?.()}
                        className="footer-button"
                        type="default"
                        size={"middle"}
                      >
                        next
                      </StyledAgree>
                    </Space>
                  </StyledTextAlign>
                ),
              }}
            >
              <div className="basic-information">
                <CustomSubTitle>Basic Information</CustomSubTitle>
                <Descriptions layout="vertical">
                  <Descriptions.Item label="Full Name (English)">
                    {/* LAM, YAN TING SOPHIE */}
                    <ProFormText
                      disabled
                      name={"fullNameEn"}
                      fieldProps={{
                        bordered: false,
                      }}
                    />
                  </Descriptions.Item>
                  <Descriptions.Item label="Full Name (Chinese)">
                    <ProFormText
                      disabled
                      name={"fullNameCn"}
                      fieldProps={{
                        bordered: false,
                      }}
                    />
                  </Descriptions.Item>
                  <Descriptions.Item label="Email">
                    {/* lamyanting@hkaa.com */}
                    <ProFormText
                      disabled
                      name={"email"}
                      fieldProps={{
                        bordered: false,
                      }}
                    />
                  </Descriptions.Item>

                  <Descriptions.Item
                    label={
                      <CenterDiv>
                        Mobile (OTP-capable) &emsp;
                        <Tooltip
                          autoAdjustOverflow={true}
                          title="Only accept local (HK) mobile registration."
                        >
                          <StyledAlertCircle />
                        </Tooltip>
                      </CenterDiv>
                    }
                  >
                    {/* <div className="mobile-input"> */}
                    <span className="area-code">+852</span>
                    <ProFormDigit
                      name={"mobile"}
                      className="mobile"
                      initialValue={identityData?.mobile}
                      fieldProps={{
                        bordered: false,
                        maxLength: 8,
                        value: mobile,
                        placeholder: "Please Input",
                        onChange: (e: any) => handleChangeMobile(e),
                      }}
                      rules={[
                        {
                          required: true,
                          message: "Please Enter mobile (OTP-capable)",
                        },
                      ]}
                    />
                    {/* </div> */}

                    {/* <span className='mobile'>92211024</span> */}
                    {/* 没有验证SMS */}
                    {!isVerified && (
                      <button
                        type="button"
                        className="send-opt"
                        onClick={() => handleSendOpt()}
                      >
                        Send OTP
                      </button>
                    )}

                    {/* 已经验证SMS */}

                    {isVerified && (
                      <button
                        type="button"
                        disabled={isVerified}
                        //className= {isVerified? 'send-opt' : 'verified-opt'}
                        className="verified-opt"
                      >
                        <span className="verified">Verified</span>
                        <div className="tick-circle" />
                      </button>
                    )}
                  </Descriptions.Item>
                  <Descriptions.Item label="Account ID no.">
                    {identityData?.hkiaId}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label="Company"
                    contentStyle={{ display: "flex", flexDirection: "column" }}
                  >
                    <ProFormSelect
                      style={{ width: "100%" }}
                      name="select"
                      fieldProps={{
                        size: "large",
                        value: selectedValue,
                        defaultValue: identityData?.companyId,
                        onChange: handleSelectChange,
                      }}
                      options={[
                        {
                          label: "Hong Kong Airport Authority",
                          value: "2de8f2a6-f71a-46bb-8b9b-3676bee91165",
                        },
                        { label: "Ground Staff", value: "option2" },
                        { label: "Hong Kong Crew Member", value: "option3" },
                        { label: "Other", value: "option4" },
                      ]}
                    ></ProFormSelect>
                    {selectedValue === "option2" && (
                      <ProFormCheckbox
                        name="crewMember"
                        // fieldProps={{ onChange: handleCheckboxChange }}
                      >
                        I am a crew member.
                        <Tooltip
                          placement="bottom"
                          autoAdjustOverflow={true}
                          title="Upload crew member certificate is a must"
                        >
                          <StyledAlertCircle />
                        </Tooltip>
                      </ProFormCheckbox>
                    )}
                    {selectedValue === "option3" && (
                      <ProFormCheckbox name="crewMember">
                        I am a crew member.
                        <Tooltip
                          placement="bottom"
                          autoAdjustOverflow={true}
                          title="Upload crew member certificate is a must"
                        >
                          <StyledAlertCircle />
                        </Tooltip>
                      </ProFormCheckbox>
                    )}
                    {selectedValue === "option4" && (
                      <ProFormText
                        width="md"
                        name="specify"
                        placeholder={"Please Enter"}
                        label="Specify"
                      />
                    )}
                  </Descriptions.Item>
                </Descriptions>
              </div>
            </ProForm>
          </div>
          <Modal
            width={"560px"}
            title=""
            className="verify-mobile-number"
            open={isModalOpen}
            onCancel={handleCancel}
            footer={null}
          >
            <div className="modal-title">Verify Your Mobile Number</div>
            <div className="modal-content">
              <div className="modal-text">
                Please enter the One-Time Password you received via SMS.
              </div>
              <div className="modal-input">
                {optCode.map((digit, index) => (
                  <input
                    style={isValidFail ? { border: "2px solid #C02020" } : {}}
                    className="input-digit"
                    key={index}
                    type="text"
                    maxLength={1}
                    value={digit}
                    onKeyDown={(e) => handleKeyDown(index, e)}
                    onChange={(e) => handleChange(index, e.target.value)}
                    ref={(ref) => handleInputRef(index, ref)}
                  />
                ))}
              </div>
              {optError && <div className="opt-error-message">{optError}</div>}
              <div className="resend-opt">
                <div className="resend-img" onClick={handleSendOpt} />
                <span className="seconds">{countdown}s</span>
                <span className="resend-text">Resend OTP code</span>
              </div>
            </div>
            <Space
              style={{ display: "flex", justifyContent: "center" }}
              size={"large"}
            >
              <StyledCancel
                onClick={handleCancel}
                type="default"
                size={"middle"}
              >
                Cancel
              </StyledCancel>
              <StyledAgree
                // onClick={handleContinue}
                type="default"
                size={"middle"}
              >
                Continue
              </StyledAgree>
            </Space>
          </Modal>
        </div>
      </PaddingContent>
    </>
  );
};

export default IdentityVerification;
